/**
 *作者：Wanghong
 *
 */



var commList =null;
    let user =JSON.parse(sessionStorage.getItem("user"));
    if (user==null){
        location.href="/pages/login.html";
    }
    $("#userName").html("尊敬的"+user.username+"先生，欢迎光临本店");
    console.info(user);
    let url = "/sTrolley/showList";
    let data ={"userid":user.userid};
$.ajax({
    async:false, //true异步.  false 同步
    type:"POST", //请求方式
    url:url,    //请求的路径
    data:data,  //请求的参数
    dataType:"json", //返回类型
    success:function(res){ //成功回调函数
        console.info(res);
        if (res.resp==1){
            commList=res.data;
            console.info(commList);
        }
    },error:function(){ //失败的回调函数

    }
});

$.each(commList,function (index,item) {
    let ul = "<ul class=\"order_lists\">\n" +
        "                <li class=\"list_chk\">\n" +
        "                    <input type=\"checkbox\" id='checkbox_"+index+"' class=\"son_check\">\n" +
        "                    <label for='checkbox_"+index+"'></label>\n" +
        "                </li>\n" +
        "                <li class=\"list_con\">\n" +
        "                    <div class=\"list_img\"><a href=\"javascript:;\"><img src='"+item.commodity.coimg+"' alt='图片'></a></div>\n" +
        "                    <div class=\"list_text\"><a href=\"javascript:;\">"+item.commodity.coremark+"</a></div>\n" +
        "                </li>\n" +
        "                <li class=\"list_info\">\n" +
        "                    <p>"+item.commodity.coname+"</p>\n" +
        "                    <p><input type='hidden' name='trId' class='trId' value='"+item.trid+"'></p>\n" +
        "                </li>\n" +
        "                <li class=\"list_price\">\n" +
        "                    <p class=\"price\">￥"+item.commodity.comoney+"</p>\n" +
        "                </li>\n" +
        "                <li class=\"list_amount\">\n" +
        "                    <div class=\"amount_box\">\n" +
        "                        <a href=\"javascript:;\" class=\"reduce reSty\">-</a>\n" +
        "                        <input type=\"text\" value='"+item.conum+"' class=\"sum\">\n" +
        "                        <a href=\"javascript:;\" class=\"plus\">+</a>\n" +
        "                    </div>\n" +
        "                </li>\n" +
        "                <li class=\"list_sum\">\n" +
        "                    <p class=\"sum_price\">￥"+item.cosum+"</p>\n" +
        "                </li>\n" +
        "                <li class=\"list_op\">\n" +
        "                    <p class=\"del\"><a href=\"javascript:;\" class=\"delBtn\">移除商品</a></p>\n" +
        "                </li>\n" +
        "            </ul>";

        $(".order_content").append(ul);

})

console.info(commList);
var deleteGoods = null


$(function () {

    //全局的checkbox选中和未选中的样式
    var $allCheckbox = $('input[type="checkbox"]'),     //全局的全部checkbox
        $wholeChexbox = $('.whole_check'),
        $cartBox = $('.cartBox'),                       //每个商铺盒子
        $shopCheckbox = $('.shopChoice'),               //每个商铺的checkbox
        $sonCheckBox = $('.son_check');                 //每个商铺下的商品的checkbox
    $allCheckbox.click(function () {
        if ($(this).is(':checked')) {
            $(this).next('label').addClass('mark');
        } else {
            $(this).next('label').removeClass('mark')
        }
    });

    //===============================================全局全选与单个商品的关系================================
    $wholeChexbox.click(function () {
        var $checkboxs = $cartBox.find('input[type="checkbox"]');
        if ($(this).is(':checked')) {
            $checkboxs.prop("checked", true);
            $checkboxs.next('label').addClass('mark');
        } else {
            $checkboxs.prop("checked", false);
            $checkboxs.next('label').removeClass('mark');
        }
        totalMoney();
    });


    $sonCheckBox.each(function () {
        $(this).click(function () {
            if ($(this).is(':checked')) {
                //判断：所有单个商品是否勾选
                var len = $sonCheckBox.length;
                var num = 0;
                $sonCheckBox.each(function () {
                    if ($(this).is(':checked')) {
                        num++;
                    }
                });
                if (num == len) {
                    $wholeChexbox.prop("checked", true);
                    $wholeChexbox.next('label').addClass('mark');
                }
            } else {
                //单个商品取消勾选，全局全选取消勾选
                $wholeChexbox.prop("checked", false);
                $wholeChexbox.next('label').removeClass('mark');
            }
            totalMoney();
        })
    })



    //=======================================每个店铺checkbox与全选checkbox的关系/每个店铺与其下商品样式的变化===================================================

    //店铺有一个未选中，全局全选按钮取消对勾，若店铺全选中，则全局全选按钮打对勾。
    $shopCheckbox.each(function () {
        $(this).click(function () {
            if ($(this).is(':checked')) {
                //判断：店铺全选中，则全局全选按钮打对勾。
                var len = $shopCheckbox.length;
                var num = 0;
                $shopCheckbox.each(function () {
                    if ($(this).is(':checked')) {
                        num++;
                    }
                });
                if (num == len) {
                    $wholeChexbox.prop("checked", true);
                    $wholeChexbox.next('label').addClass('mark');
                }

                //店铺下的checkbox选中状态
                $(this).parents('.cartBox').find('.son_check').prop("checked", true);
                $(this).parents('.cartBox').find('.son_check').next('label').addClass('mark');
            } else {
                //否则，全局全选按钮取消对勾
                $wholeChexbox.prop("checked", false);
                $wholeChexbox.next('label').removeClass('mark');

                //店铺下的checkbox选中状态
                $(this).parents('.cartBox').find('.son_check').prop("checked", false);
                $(this).parents('.cartBox').find('.son_check').next('label').removeClass('mark');
            }
            totalMoney();
        });
    });




    //=================================================商品数量==============================================
    var $plus = $('.plus'),
        $reduce = $('.reduce'),
        $all_sum = $('.sum');
    $plus.click(function () {
        let trId= $(this).parents('.order_lists').find('.trId').val();
        console.info(trId);
        let url ="/sTrolley/update";
        let data = {"trid":trId,"fu":"+"};
        $.post(url,data,function (res) {
            console.info(res);
            if (res.resp==1){
                console.info("修改成功");
            } else {
                console.info("修改失败");
            }
        },"json");

        var $inputVal = $(this).prev('input'),
            $count = parseInt($inputVal.val())+1,//数量
            $obj = $(this).parents('.amount_box').find('.reduce'),
            $priceTotalObj = $(this).parents('.order_lists').find('.sum_price'),
            $price = $(this).parents('.order_lists').find('.price').html(),  //单价
            $priceTotal = $count*parseFloat($price.substring(1));
        console.info("单价"+$price);
        console.info("数量"+$count);
        $inputVal.val($count);
        $priceTotalObj.html('￥'+$priceTotal);



        if($inputVal.val()>1 && $obj.hasClass('reSty')){
            $obj.removeClass('reSty');
        }
        totalMoney();
    });

    $reduce.click(function () {
        let trId= $(this).parents('.order_lists').find('.trId').val();
        console.info(trId);
        let url ="/sTrolley/update";
        let data = {"trid":trId,"fu":"-"};
        $.post(url,data,function (res) {
            console.info(res);
            if (res.resp==1){
                console.info("修改成功");
            } else {
                console.info("修改失败");
            }
        },"json");
        var $inputVal = $(this).next('input'),
            $count = parseInt($inputVal.val())-1,
            $priceTotalObj = $(this).parents('.order_lists').find('.sum_price'),
            $price = $(this).parents('.order_lists').find('.price').html(),  //单价
            $priceTotal = $count*parseFloat($price.substring(1));
        if($inputVal.val()>1){
            $inputVal.val($count);
            $priceTotalObj.html('￥'+$priceTotal);
        }
        if($inputVal.val()==1 && !$(this).hasClass('reSty')){
            $(this).addClass('reSty');
        }
        totalMoney();
    });

    $all_sum.keyup(function () {
        var $count = 0,
            $priceTotalObj = $(this).parents('.order_lists').find('.sum_price'),
            $price = $(this).parents('.order_lists').find('.price').html(),  //单价
            $priceTotal = 0;
        if($(this).val()==''){
            $(this).val('1');
        }
        $(this).val($(this).val().replace(/\D|^0/g,''));
        $count = $(this).val();
        $priceTotal = $count*parseFloat($price.substring(1));
        $(this).attr('value',$count);
        $priceTotalObj.html('￥'+$priceTotal);
        totalMoney();
    })

    //======================================移除商品========================================

    var $order_lists = null;
    var $order_content = '';
    let trId =null;
    $('.delBtn').click(function () {
        $order_lists = $(this).parents('.order_lists');
        $order_content = $order_lists.parents('.order_content');
        $('.model_bg').fadeIn(300);
        $('.my_model').fadeIn(300);
        trId= $(this).parents('.order_lists').find('.trId').val();
        console.info(trId);

    });

    //关闭模态框
    $('.closeModel').click(function () {
        closeM();
    });
    $('.dialog-close').click(function () {
        closeM();
    });
    function closeM() {
        $('.model_bg').fadeOut(300);
        $('.my_model').fadeOut(300);
    }
    //确定按钮，移除商品
    $('.dialog-sure').click(function () {
        $order_lists.remove();
        if($order_content.html().trim() == null || $order_content.html().trim().length == 0){
            $order_content.parents('.cartBox').remove();

        }
        console.info("开始删除");
        let url = "/sTrolley/delete";
        let data = {"trid":trId};
        $.post(url,data,function (res) {
            console.info(res);
            if (res.resp==1){
                console.info("删除成功");
            } else {
                console.info("删除失败");
            }
        },"json")
        closeM();
        $sonCheckBox = $('.son_check');
        totalMoney();

    })

    //======================================总计==========================================

    function totalMoney() {
        var total_money = 0;
        var total_count = 0;
        var calBtn = $('.calBtn a');
        $sonCheckBox.each(function () {
            if ($(this).is(':checked')) {
                console.info($(this).parents('.order_lists').find('.sum_price').html());
                console.info($(this).parents('.order_lists').find('.sum').val());
                var goods = parseFloat($(this).parents('.order_lists').find('.sum_price').html().substring(1));
                var num =  parseFloat($(this).parents('.order_lists').find('.sum').val());
                total_money += goods;
                total_count += num;
                console.info("单价"+goods);
                console.info("单1价"+total_money);
                console.info("数量"+num);
                console.info("数1量"+total_count);

            }
        });
        $('.total_text').html('￥'+total_money);
        $('.piece_num').html(total_count);

        // console.log(total_money,total_count);

        if(total_money!=0 && total_count!=0){
            if(!calBtn.hasClass('btn_sty')){
                calBtn.addClass('btn_sty');
            }
        }else{
            if(calBtn.hasClass('btn_sty')){
                calBtn.removeClass('btn_sty');
            }
        }
    }


});